﻿App.define('user', function() {
	var user = {}, currentUser = {}, isAuth = false;

	user.isAuth = function () {
		return isAuth;
	};

	user.name = function() {
		return currentUser.name;
	};

	user.color = function () {
		return currentUser.color;
	};

	user.init = function(userData, auth) {
		currentUser.name = userData.name;
		currentUser.color = userData.color;
		isAuth = auth === true;
	};

	user.changeName = function (newName) {
		if (typeof newName !== 'undefined' &&
			newName !== null &&
			/^[А-яA-z0-9_-]{3,15}$/g.test(newName)) {

			Ajax.post({
				url: '/changeName',
				data: {
					name: newName,
					__RequestVerificationToken: App.getVerificationToken()
				},
				done: function() {
					App.alert.info(Localization.NameChanged);
				}
			});

			currentUser.name = newName;

			return true;
		} else {
			if (typeof newName === 'undefined' || newName === null) {
				App.alert.danger(Localization.NameValidationRequired);
			}else if (newName.length < 3) {
				App.alert.danger(Localization.NameValidationMinLength);
			}else if (newName.length > 15) {
				App.alert.danger(Localization.NameValidationMaxLength);
			} else {
				App.alert.danger(Localization.NameValidationRegex);
			}
		}

		return false;
	};

	App.config.userData && user.init(App.config.userData, true);

	return user;
});